package com.springboot.security.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.springboot.security.config.CacheFactory;
import com.springboot.security.entity.Customer;
import com.springboot.security.entity.DistributionMember;
import com.springboot.security.entity.Member;
import com.springboot.security.form.Identity;
import com.springboot.security.po.AuthenticationOpt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;

@RestController
@RequestMapping("/authentication")
public class AuthenticationController {

    @Autowired
    private AuthenticationOpt authenticationOpt;

    @PostMapping("/logout")
    public void logout(@RequestBody @Valid Identity identity){
        // 根据ID获取对象
        if(identity.getType() == 1){
            Customer build = Customer.builder().id("1").name("张三").nickname("小小").build();
            build.logout(authenticationOpt);
        } else if(identity.getType() == 2){
            Member build = Member.builder().id("1").name("李四").nickname("大大").build();
            build.logout(authenticationOpt);
        } else if(identity.getType() == 3){
            DistributionMember build = DistributionMember.builder().id("1").name("王武").nickname("中中").build();
            build.logout(authenticationOpt);
        }
    }

    @PostMapping("/register/customer")
    public void register(@RequestBody Customer customer){
        Gson gson = new GsonBuilder().create();
        CacheFactory.getCache().put("currentCustomer".concat(customer.getId()), gson.toJson(customer, Customer.class));
    }

    @PostMapping("/register/member")
    public void register(@RequestBody Member member){
        Gson gson = new GsonBuilder().create();
        CacheFactory.getCache().put("currentMember".concat(member.getId()), gson.toJson(member, Member.class));
    }

    @PostMapping("/register/distributionManager")
    public void register(@RequestBody DistributionMember distributionMember){
        Gson gson = new GsonBuilder().create();
        CacheFactory.getCache().put("currentDistributionMember".concat(distributionMember.getId()), gson.toJson(distributionMember, DistributionMember.class));
    }

    @GetMapping("/query")
    public Map<String, String> queryAll(){
        ConcurrentMap<String, String> stringStringConcurrentMap = CacheFactory.getCache().asMap();
        stringStringConcurrentMap.forEach((key, value) -> {
            System.out.println(key);
            System.out.println(value);
        });
        return stringStringConcurrentMap;
    }




}
